
const Layout = () => import("@/layout/index.vue");

const isRoute = (path: string) => {
  return !path.includes('/components')
}
const getRouteName = (path: string) => {
  const name = path.split('/').map(v => {
    v = v.slice(0, 1).toLocaleUpperCase() + v.slice(1)
    return v
  }).join('')
  return name
}

export const readDirComponents = () => {
  const modules = import.meta.glob("@/views/**/**.vue");
  const routeMap: Record<string, any> = {}
  for (const path in modules) {
    const result = path.match(/.*\/(.+).vue$/);
    if (result && isRoute(result[0])) {
      // const name = result[0];
      const routePath = result[0].replace('../views', '').replace('/index.vue', '')
      const name = getRouteName(routePath)
      const component = modules[path];
      const level = routePath.split('/').length - 1
      const item = {
        path: routePath,
        name,
        component,
        meta: {
          title: name,
          hidden: false,
          level,
        }
      }
      let parentPath = ''
      // 非顶级菜单
      if (level > 1) {
        // 获取顶级菜单路径
        parentPath = routePath.split('/').slice(1, 2).join('/')
        if (!routeMap[parentPath]) {
          routeMap[parentPath] = {
            path: parentPath,
            name: getRouteName(parentPath),
            component: Layout,
            meta: {
              title: getRouteName(parentPath),
              hidden: false,
              level: level - 1,
            },
            redirect: item.path,
            children: [item]
          }
        } else {
          routeMap[parentPath].children = [
            ...routeMap[parentPath].children,
            item
          ]
        }
      } else {
        routeMap[routePath] = item
      }
    }
  }
  console.log('routeMap: ', routeMap);
  return routeMap
};

export const generateRoutes = () => {
  readDirComponents()
};
